
import datetime
import time

import pymysql
import configparser
import logging
import paho.mqtt.client as mqtt


class Singleton(object):
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}

    def __call__(self):
        if self._cls not in self._instance:
            self._instance[self._cls] = self._cls()
        return self._instance[self._cls]


@Singleton
class MysqlManager(object):

    def __init__(self):
        config = configparser.ConfigParser()
        config.read('properties.conf')
        mysql = config['mysql']
        self.connect = pymysql.connect(
            host=mysql['host'],
            port=int(mysql['port']),
            db=mysql['db'],
            user=mysql['user'],
            passwd=mysql['passwd'],
            charset='utf8',
            use_unicode=True
        )

    def reconnection(self):
        try:
            print(">>>>>>> 开始重连")
            self.connect.connect()
            self.cursor = self.connect.cursor()
        except Exception as e:
            print(">>>>>>> 数据库重连失败:", e)

    def insert_data(self, location, centigrade, humidity, create_time, remark):
        insert = "insert into t_temperature (location, centigrade, humidity,create_time, remark) Values ('{}', {}, {}, '{}', '{}')" \
            .format(location, float(humidity), float(centigrade), create_time, remark)
        print(">>>>> " + insert)
        try:
            self.connect.ping(reconnect=True)
            self.connect.cursor().execute(insert)
            self.connect.commit()
        except Exception as e:
            print(e)


def on_connect(client, userdata, flags, rc):
    print(client, userdata, flags, rc)
    client.subscribe(topic="house", qos=0)


def on_message(client, userdata, msg):
    try:
        print(">>>>> 接受：", msg.payload)
    
        mysql = MysqlManager()
        print(">>>>> Mysql 就绪")
        today_time = str(datetime.datetime.now()).split('.')[0]

        print(">>>>> 开始数据处理...")
        message_list = str(msg.payload,encoding='utf-8').split("_")
        print(">>>>> 数据处理结果：", message_list)
        if 3 != len(message_list):
            print("Message not right:", msg.playload)
            return 
        print(">>>> 开始存入...")
        today_time = datetime.datetime.strptime(today_time, '%Y-%m-%d %H:%M:%S')
        mysql.insert_data(message_list[0], message_list[1], message_list[2], today_time, "")
    except pymysql.err.InterfaceError as e:
        print(">>>> 存入异常1：", e)
        mysql.reconnection()
        mysql.insert_data(message_list[0], message_list[1], message_list[2], today_time, "")
    except Exception as e:
        print(">>>> 存入异常2：", e)
        print(e)


def create_client(config):
    try:
        client = mqtt.Client("save_subscriber")
        client.on_connect = on_connect
        client.on_message = on_message
        client.connect(config['mqtt']['host'])
        client.loop_forever()
    except Exception as e:
        logging.error(">>>>>>>> client error")
        logging.error(e)
        time.sleep(60)
        create_client(config)


if __name__ == '__main__':
    logging.basicConfig(filename='log_subscriber.log', level=logging.INFO)
    config = configparser.ConfigParser()
    config.read('properties.conf')
    try:
        print(" 开始创建Clinet....")
        create_client(config)
    except Exception as e:
        create_client(config)
        logging.error(">>>>>>>> client error")
        logging.error(e)

